#include <stdio.h>
#include <stdlib.h>
#include <time.h>

/* build an array, sort,print,destroy it. */

int *build_array(int len)
{
    int *array = malloc(len * sizeof(int) + 1);
    if (array) {
        srand(time(NULL));
        for (int i = 1; i <= len; i++) {
            int n = rand() % 64;
            array[i] = n;
        }
        array[0] = len; // save array len
    }
    return array;
}

int *print_array(int *array)
{
    if (array) {
        int len = *array;
        for (int i = 1; i <= len; i++) {
            printf("%d ", array[i]);
        }
    }
    return array;
}

void destroy_array(int *array)
{
    if (array)
        free(array);
}

void bubble_sort(int arr[], int len) {
    int i, j, temp;
    for (i = 0; i < len - 1; i++)
        for (j = 0; j < len - 1 - i; j++)
            if (arr[j] > arr[j + 1]) {
                temp = arr[j];
                arr[j] = arr[j + 1];
                arr[j + 1] = temp;
            }
}

int *sort_array(int *array)
{
    if (array)
        bubble_sort(&array[1], array[0]);
    return array;
}

int main(int argc, char *argv[])
{
    destroy_array(print_array(sort_array(build_array(10))));
    return 0;
}
